package com.morn.weibo.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.morn.weibo.R;
import com.morn.weibo.WeiboApplication;
import com.morn.weibo.http.Fanfou;
import com.morn.weibo.types.Conversation;
import com.morn.weibo.types.Message;
import com.morn.weibo.types.User;
import com.morn.weibo.utils.DateUtils;

public class ConversationListAdapter extends ArrayAdapter<Conversation> {

	private static final int resource = R.layout.view_item_conversation;
	private Fanfou fanfou;
	private LayoutInflater inflater;

	public ConversationListAdapter(Context context) {
		super(context, android.R.layout.simple_list_item_2);
		inflater = LayoutInflater.from(context);
		fanfou = WeiboApplication.getFanfou();
	}

	public void setData(List<Conversation> data) {
		clear();
		if (data != null) {
			addAll(data);
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Conversation conversation = getItem(position);
		Message message = conversation.getMessage();
		View vi = convertView;
		ViewHolder holder;
		if (convertView == null) {
			vi = inflater.inflate(resource, null);
			holder = new ViewHolder();
			holder.conversationItemPhoto = (ImageView) vi
					.findViewById(R.id.conversationItemPhoto);
			holder.conversation_item_name = (TextView) vi
					.findViewById(R.id.conversation_item_name);
			holder.conversationItemTime = (TextView) vi
					.findViewById(R.id.conversationItemTime);
			holder.conversationItemMsg = (TextView) vi
					.findViewById(R.id.conversationItemMsg);
			holder.conversationItemCount = (TextView) vi
					.findViewById(R.id.conversationItemCount);
			vi.setTag(holder);
		} else
			holder = (ViewHolder) vi.getTag();

		holder.conversationItemTime.setText(DateUtils.getDateStr(message
				.getCreated_at()));
		holder.conversationItemMsg.setText(message.getText());
		holder.conversationItemCount.setText(conversation.getMsg_num() + "");

		String otherId = conversation.getOtherid();

		User user1 = message.getSender();
		User user2 = message.getRecipient();
		User otherUser = null;
		if (otherId.equals(user1.getId())) {
			otherUser = user1;
		} else {
			otherUser = user2;
		}
		holder.conversation_item_name.setText(otherUser.getName());
		String imageUrl = otherUser.getProfile_image_url();

		if (imageUrl != null) {
			fanfou.downloadImage(imageUrl, holder.conversationItemPhoto);
		}

		return vi;
	}

	public static class ViewHolder {
		public ImageView conversationItemPhoto;
		public TextView conversation_item_name;
		public TextView conversationItemTime;
		public TextView conversationItemMsg;
		public TextView conversationItemCount;
	}

}
